using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using ContosoUniversity.Data;
using ContosoUniversity.Models;

namespace ContosoUniversity.Pages.Courses
{
    public class CreateModel : DepartmentNamePageModel
    {
        private readonly ContosoUniversity.Data.SchoolContext _context;

        public CreateModel(ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            //ViewData["DepartmentID"] = new SelectList(_context.Departmentss, "DepartmentID", "DepartmentID");
            PopulateDepartmentsDropDownList(_context);
            return Page();
        }

        [BindProperty]
        public Course Course { get; set; }

        public string ErrorMsg { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            var emptyCourse = new Course();
            try
            {
                if (await TryUpdateModelAsync<Course>(emptyCourse, "course",
                    s => s.CourseID, s => s.DepartmentID, s => s.Title, s => s.Credits))
                {
                    _context.Courses.Add(emptyCourse);

                    await _context.SaveChangesAsync();


                    return RedirectToPage("./Index");
                }

                //_context.Courses.Add(Course);
                //await _context.SaveChangesAsync();
                //return RedirectToPage("./Index");
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.Message;
            }

            // Select DepartmentID if TryUpdateModelAsync fails.
            PopulateDepartmentsDropDownList(_context, Course.DepartmentID);
            return Page();
        }
    }
}